package com.bilgeadam.shopping.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.bilgeadam.shopping.model.Product;
import com.bilgeadam.shopping.model.ShoppingItem;

/**
 *
 * @author Bora SAYINER
 * @since Jan 3, 2015 3:55:06 PM
 * @version 1.0
 */
@WebServlet(name = "ShoppingCartServlet", urlPatterns = { "/showProducts", "/showProductDescription", "/addToBasket", "/showBasket" })
public class ShoppingCartServlet extends HttpServlet {

	private final List<Product> products;

	public ShoppingCartServlet() {
		this.products = new ArrayList<Product>();
	}

	@Override
	public void init() throws ServletException {
		products.add(new Product(22114793, "CLINOMYN", "SİGARA İÇENLER İÇİN DİŞ MACUNU 75 ML", 9.50));
		products.add(new Product(
				1460122,
				"LÜX PAMUKLU ÇUBUK",
				"Lüx Pamuklu Kulak Çubuğu 100'lü,   kulak çevresindeki alanları temizler ve kurular. Bebeğinizin göz, kulak, burun ve göbek temizliğinde güvenle kullanabilirsiniz. Yüzde 100  saf pamuktan otomatik makinelerde el değmeden üretilmiş ve ambalajlanmıştır. ",
				1.05));
		products.add(new Product(1944142, "DALİN BEBEK ŞAMPUANI 750 ML",
				"Dalin Şampuan 750 ml,  formülü özel olarak geliştirilmiş bir şampuandır. Saf içeriği sayesinde bebeğinizin gözlerini yakmaz ve rahat bir banyo yapmasını sağlar.",
				12.50));
		products.add(new Product(6769971, "PROTEX ANTİBAKTERİYEL", "Protex Nemlendiricili Sıvı Sabun, 750 ml'dir. Bakterilerin %99'unu yok eder ve uzun süre koruma sağlar.", 9.75));
	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {		
		if (req.getRequestURI().endsWith("showProducts")) {
			printShowProductsPage(resp);
		} else if (req.getRequestURI().endsWith("showProductDescription")) {
			printShowProductDescription(req, resp);
		} else if (req.getRequestURI().endsWith("showBasket")) {
			printShowBasket(req, resp);
		}
	}

	@SuppressWarnings("unchecked")
	private void printShowBasket(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession();
		List<ShoppingItem> shoppingItems = (List<ShoppingItem>) session.getAttribute("basket");
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("<!DOCTYPE html>");
		stringBuffer.append("<html>");
		{
			stringBuffer.append("<head>");
			{
				stringBuffer.append("<meta charset='UTF-8'>");
				stringBuffer.append("<link rel='stylesheet' href='http://yui.yahooapis.com/pure/0.5.0/pure-min.css'>");
				stringBuffer.append("<title>Products</title>");
			}
			stringBuffer.append("</head>");
			stringBuffer.append("<body>");
			{
				stringBuffer.append("<h1>Sepetim</h1>");
				stringBuffer.append("<table class='pure-table pure-table-bordered'>");
				{
					stringBuffer.append("<thead>");
					{
						stringBuffer.append("<tr>");
						{
							stringBuffer.append("<th>Ürün Adı</th>");
							stringBuffer.append("<th>Adet</th>");
						}
						stringBuffer.append("</tr>");
					}
					stringBuffer.append("</thead>");
					stringBuffer.append("<tbody>");
					{
						if (shoppingItems.size() > 0) {
							for (int i = 0; i < shoppingItems.size(); i++) {
								ShoppingItem item = shoppingItems.get(i);
								stringBuffer.append("<tr>");
								{
									stringBuffer.append("<td>" + item.getProduct().getName() + "</td>");
									stringBuffer.append("<td>" + item.getQuantity() + "</td>");
								}
								stringBuffer.append("</tr>");
							}
						} else {
							stringBuffer.append("<h1>Sepet Boş</h1>");
						}
					}
					stringBuffer.append("</tbody>");
					stringBuffer.append("<br/><a href='showProducts'>Ürünleri Göster</a>");
				}
			}
			stringBuffer.append("</body>");
		}
		stringBuffer.append("</html>");
		resp.getWriter().print(stringBuffer.toString());
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		int quantity = Integer.valueOf(req.getParameter("quantity"));
		Product product = findProductById(Integer.valueOf(req.getParameter("id")));
		HttpSession session = req.getSession();
		List<ShoppingItem> shoppingItems = null;
		shoppingItems = (List<ShoppingItem>) session.getAttribute("basket");
		if (shoppingItems == null) {
			shoppingItems = new ArrayList<ShoppingItem>();
			session.setAttribute("basket", shoppingItems);
		}
		shoppingItems.add(new ShoppingItem(product, quantity));
		printShowProductsPage(resp);
	}

	private void printShowProductDescription(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		Product product = findProductById(Integer.valueOf(req.getParameter("id")));
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("<!DOCTYPE html>");
		stringBuffer.append("<html>");
		{
			stringBuffer.append("<head>");
			{
				stringBuffer.append("<meta charset='UTF-8'>");
				stringBuffer.append("<link rel='stylesheet' href='http://yui.yahooapis.com/pure/0.5.0/pure-min.css'>");
				stringBuffer.append("<title>Products</title>");
			}
			stringBuffer.append("</head>");
			stringBuffer.append("<body>");
			{
				stringBuffer.append("<h1>Ürün Detayı</h1>");
				stringBuffer.append("<table class='pure-table pure-table-bordered'>");
				{
					stringBuffer.append("<thead>");
					{
						stringBuffer.append("<tr>");
						{
							stringBuffer.append("<th>Ürün Adı</th>");
							stringBuffer.append("<th>Açıklama</th>");
							stringBuffer.append("<th>Fiyatı</th>");
						}
						stringBuffer.append("</tr>");
					}
					stringBuffer.append("</thead>");
					stringBuffer.append("<tbody>");
					{
						stringBuffer.append("<tr>");
						{
							stringBuffer.append("<td>" + product.getName() + "</td>");
							stringBuffer.append("<td>" + product.getDescription() + " TL</td>");
							stringBuffer.append("<td>" + product.getPrice() + "</td>");
						}
					}
					stringBuffer.append("</tr>");
					stringBuffer.append("</tbody>");
				}
				stringBuffer.append("</table>");
				stringBuffer.append("<form action='addToBasket' method='post'>");
				{
					stringBuffer.append("<input type='text' name='quantity'>");
					stringBuffer.append("<input type='hidden' name='id' value='" + product.getId() + "'>");
					stringBuffer.append("<input type='submit' value='Sepete Ekle' class='pure-button pure-button-primary'>");
				}
				stringBuffer.append("</form>");

				stringBuffer.append("<br/><a href='showProducts'>Ürünleri Göster</a>");
			}
			stringBuffer.append("</body>");
		}
		stringBuffer.append("</html>");
		resp.getWriter().print(stringBuffer.toString());
	}

	private void printShowProductsPage(HttpServletResponse resp) throws IOException {
		resp.setContentType("text/html");
		resp.setCharacterEncoding("UTF-8");
		StringBuffer stringBuffer = new StringBuffer();
		stringBuffer.append("<!DOCTYPE html>");
		stringBuffer.append("<html>");
		{
			stringBuffer.append("<head>");
			{
				stringBuffer.append("<meta charset='UTF-8'>");
				stringBuffer.append("<link rel='stylesheet' href='http://yui.yahooapis.com/pure/0.5.0/pure-min.css'>");
				stringBuffer.append("<title>Products</title>");
			}
			stringBuffer.append("</head>");
			stringBuffer.append("<body>");
			{
				stringBuffer.append("<h1>Ürünler</h1>");
				stringBuffer.append("<table class='pure-table pure-table-bordered'>");
				{
					stringBuffer.append("<thead>");
					{
						stringBuffer.append("<tr>");
						{
							stringBuffer.append("<th>#</th>");
							stringBuffer.append("<th>Ürün Adı</th>");
							stringBuffer.append("<th>Fiyatı</th>");
							stringBuffer.append("<th>#</th>");
						}
						stringBuffer.append("</tr>");
					}
					stringBuffer.append("</thead>");
					stringBuffer.append("<tbody>");
					{
						for (int i = 0; i < products.size(); i++) {
							Product product = products.get(i);
							if (i % 2 == 0) {
								stringBuffer.append("<tr class='pure-table-odd'>");
							} else {
								stringBuffer.append("<tr>");
							}
							{
								stringBuffer.append("<td>" + (i + 1) + "</td>");
								stringBuffer.append("<td>" + product.getName() + "</td>");
								stringBuffer.append("<td>" + product.getPrice() + " TL</td>");
								stringBuffer.append("<td><a href=showProductDescription?id=" + product.getId() + ">Açıklama</a></td>");
							}
							stringBuffer.append("</tr>");
						}
					}
					stringBuffer.append("</tbody>");
				}
				stringBuffer.append("</table>");
				stringBuffer.append("<br/><a href='showBasket'>Sepeti Göster</a>");
			}
			stringBuffer.append("</body>");
		}
		stringBuffer.append("</html>");
		resp.getWriter().print(stringBuffer.toString());
	}

	// Normalde veritabanı üzerinden gelecek olan veriyi simule ediyoruz
	private Product findProductById(int id) {
		Product product = null;
		for (Product current : products) {
			if (current.getId() == id) {
				product = current;
				break;
			}
		}
		return product;
	}
}
